package org.van.blog.controller.admin;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.github.pagehelper.PageInfo;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.van.blog.constant.LogActions;
import org.van.blog.constant.WebConst;
import org.van.blog.controller.BaseController;
import org.van.blog.dto.StatisticsDto;
import org.van.blog.exception.BusinessException;
import org.van.blog.model.CommentDomain;
import org.van.blog.model.ContentDomain;
import org.van.blog.model.LogDomain;
import org.van.blog.model.UserDomain;
import org.van.blog.service.log.LogService;
import org.van.blog.service.site.SiteService;
import org.van.blog.service.user.UserService;
import org.van.blog.utils.APIResponse;
import org.van.blog.utils.GsonUtils;
import org.van.blog.utils.TaleUtils;

@Controller("adminIndexController")
@RequestMapping(value = "/admin")
public class IndexController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(IndexController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private LogService logService;

    @Autowired
    private SiteService siteService;

    @GetMapping(value = { "", "/index" })
    public String index(HttpServletRequest request) {
        LOGGER.info("Enter admin index method");
        List<CommentDomain> comments = siteService.getComments(5);
        List<ContentDomain> contents = siteService.getNewArticles(5);
        StatisticsDto statistics = siteService.getStatistics();
        PageInfo<LogDomain> logs = logService.getLogs(1, 5);
        List<LogDomain> list = logs.getList();

        request.setAttribute("comments", comments);
        request.setAttribute("articles", contents);
        request.setAttribute("statistics", statistics);
        request.setAttribute("logs", list);
        LOGGER.info("Exit admin index method");

        return "admin/index";
    }

    @GetMapping(value = "/profile")
    public String profile() {
        return "admin/profile";
    }

    @PostMapping(value = "/profile")
    @ResponseBody
    public APIResponse<?> saveProfile(
            @RequestParam String screenName,
            @RequestParam String email,
            HttpServletRequest request,
            HttpSession session) {
        UserDomain users = this.user(request);
        if (StringUtils.isNotBlank(screenName) && StringUtils.isNotBlank(email)) {
            UserDomain temp = new UserDomain();
            temp.setUid(users.getUid());
            temp.setScreenName(screenName);
            temp.setEmail(email);
            userService.updateUserInfo(temp);
            logService.addLog(LogActions.UP_INFO.getAction(), GsonUtils.toJsonString(temp), request.getRemoteAddr(),
                    this.getUid(request));
            UserDomain originAL = (UserDomain) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
            originAL.setScreenName(screenName);
            originAL.setEmail(email);
            session.setAttribute(WebConst.LOGIN_SESSION_KEY, originAL);
        }
        return APIResponse.success();
    }

    @PostMapping(value = "/password")
    @ResponseBody
    public APIResponse<?> upPwd(
            @RequestParam String oldPassword,
            @RequestParam String newPassword,
            HttpServletRequest request,
            HttpSession session) {
        UserDomain users = this.user(request);
        if (StringUtils.isBlank(oldPassword) || StringUtils.isBlank(newPassword)) {
            return APIResponse.fail("Please check if the information is right!");
        }

        if (!users.getPassword().equals(TaleUtils.MD5encode(users.getUsername() + oldPassword))) {
            return APIResponse.fail("Old Password Incorrect!");
        }

        if (newPassword.length() < 6 || newPassword.length() > 18) {
            return APIResponse.fail("Length between 6 to 18!");
        }

        try {
            UserDomain temp = new UserDomain();
            temp.setUid(users.getUid());
            String pwd = TaleUtils.MD5encode(users.getUsername() + newPassword);
            temp.setPassword(pwd);
            userService.updateUserInfo(temp);
            logService.addLog(LogActions.UP_PWD.getAction(), null, request.getRemoteAddr(), this.getUid(request));

            UserDomain originAL = (UserDomain) session.getAttribute(WebConst.LOGIN_SESSION_KEY);
            originAL.setPassword(pwd);
            session.setAttribute(WebConst.LOGIN_SESSION_KEY, originAL);
            return APIResponse.success();
        } catch (Exception e) {
            String msg = "Failed to change password!";
            if (e instanceof BusinessException) {
                msg = e.getMessage();
            } else {
                LOGGER.error(msg, e);
            }
            return APIResponse.fail(msg);
        }
    }

}
